<?php
session_start();
include 'inc/db_connect.php';
include 'inc/db_op.php';
include 'inc/html_op.php';

$page_title = 'Query';

function get_trace_link($str) {
  $where = "where is_trip_out =1 ";
  
  if(strpos($str,"当前出差")===false) {
    $where .= "and assignto in (select id from user_info where name = '".$_SESSION['name']."')";
  } else {
    $where .= "and progress < 100";
  }
  
  $sql = "select longtitude, latitude from china_cities where city in ";
  $sql .= " (select distinct customer_location from project_info where id in ";
  $sql .= "(select distinct project_id from task_info ".$where."))";
  
  $rows = db_get($sql);
  
  $markers="markers=32.03,118.46";
  foreach($rows as $row) {
    $markers .= "|".$row['latitude'].",".$row['longtitude'];
  }

  $url = "http://maps.google.com/maps/api/staticmap?center=36.38,101.48&visible=32.03,118.46&size=640x480&sensor=false&".$markers;
    
  return $url;
}

function show_2012newyear_greetings() {
  if(isset($_SESSION["logged"]) && ((1==$_SESSION["user_id"])||((strtotime('2011-12-31 15:00')-time()<0)&&(strtotime('2012-01-03 15:00')-time()>0)))) {
    
    echo "<p>";
    //echo date("h:i");
    //echo time().",";
    //echo strtotime('2011-12-31 15:00')-time();
    echo "</p>";
    echo "<p class='newyear'>";
    echo "当收起2011年的台历，一年的时光匆匆流走。<br/>";
    echo "回首这一年，最不能忘记的是你和每一位高软部兄弟姐妹的忙碌的身影。<br/>";
    echo "下面的地图是我为你定制的新年礼物，它记录了你这一年出差的足迹。<br/>";
    echo "请珍藏，它记录了你的辛劳和智慧，也希望足迹带给了你沉甸甸的收获和美好的回忆。<br/>";
    echo "</p>";
    $url = get_trace_link("足迹2011");
    echo "<img src='".$url."'/>";
    echo "<p class='newyear'>";
    //echo "因为有了你，我们的团队才更加精彩，<br/>";
    //echo "因为有了你，我们的拼搏更有意义。<br/>";
    //echo "2012，我们继续携手共进。<br/>";
    //echo "</p><p class='newyear'>";
    echo "请接受我给你和你家人的最美好的新年祝福：<br/>";
    echo "健康、美丽、幸运、幸福！ <br/>";
    echo "</p><p class='newyear'>";
    echo "恭贺 新年快乐！ 龚成明";
    echo "</p>";

  }
}

function gen_query_form() {
  $html_str = '
<form id="qform" name="qform" method="post">
  <p color="#f0"><label>
  <input type="search" name="search_str" id="search_str" placeholder="请输入合同号、WBS号或项目名称" required size=34/>
  </label>
  <label>
  <button type="submit" name="button" id="button">查询</button>
  </label>
</form> </p> ' ;
  return $html_str;
}

function get_query_str() {
  $query_str = "";
  if(strcmp(key($_GET),"") != 0) {
    $query_str=key($_GET);
  } else {
    $query_str=$_POST['search_str'];
  }
  return $query_str;
}

function get_search_str($query_str) {
  $search_str = ($query_str != "" ? $query_str : "没有输入");
  if(isset($_SESSION['logged']) && isset($_SESSION['name']) && (0 == strcmp($search_str, '我') || 0==strcmp($search_str,'me'))) {
    $search_str = $_SESSION['name'];
  }
  return $search_str;
}

function get_commit_flag_str($project_id, $committed) {
  $flag_str = "1";
  if(!$committed) {
    if(isset($_SESSION['user_id']) && is_manager($_SESSION['user_id']) || is_administrator($_SESSION['user_id'])) {
      $href = 'javascript:confirm("真的要投运吗？")&&submit_a_value("commit_project_id",'.$project_id.');';
      $flag_str = "<a href=$href>0</a>";
	} else {
      $flag_str = "0";
	}
  }
  return $flag_str;
}

function get_dwno_str($project_id, $dw_no) {
  $href = 'javascript:submit_a_value("project_id",'.$project_id.',"project.php")';
  return isset($_SESSION['logged']) ? "<a href=$href>$dw_no</a>" : $dw_no;
}

function proceed_project_commitment() {
  if(isset($_POST['commit_project_id'])) {
    db_update('project_info', array("committed"=>1), $_POST['commit_project_id']);
    $html_str .= '<center><p>已成功设置投运标志。</p></center>';
  }  
}

function log_query_record() {
  if(isset($_POST['button'])) {
    $user = isset($_SESSION["name"]) ? $_SESSION["name"] : "not logged";
    mysql_query("insert into query_log(user, query_str) values('".$user."', '".$_POST['search_str']."')");
  }
}

function log_visit() {
  mysql_query("update visit_st set count = count + 1 where page like 'mainpage'");
}

function gen_query_results($sql) {
  $html_str = "";
  $rows = db_get($sql);
  $num = count($rows);

  if($num == 0) {
    $html_str .= '<p>没有查找到记录。</p>';
  } else {
    $html_str .= '<p>查找到'.$num.'条记录。</p>';
        
    $html_str .= '<table border=1>';
    $html_str .= '<tr><th>DW合同号</th><th>WBS号</th><th>项目名称</th><th>投运标志</th><th>工作小时数</th></tr>';

    foreach($rows as $row) {
      $project_id = $row['project_id'];

      $html_str .= '<tr><td>'.get_dwno_str($project_id, $row['dw_no']).'</td><td>';
      $html_str .= $row['wbs_no'].'</td><td style="width:260px;"> '.$row['project_name'].'</td><td><center>'.
      get_commit_flag_str($project_id, $row['committed']).'</center></td>';
      $html_str .= '<td align="right">'.$row['hours'].'</td>';
    }

    $html_str .= '</table>';
  }
  
  return $html_str;
}

function gen_sql_by_search_str($search_str) {
  $sql = "select project_info.id project_id, dw_no, wbs_no, project_name, committed, sum(work_hours) hours ";
  $sql .= " from project_info left join task_info on project_info.id = task_info.project_id ";
  $sql .= " left join work_log on task_info.id = work_log.task_id ";
      
  $group .= " group by project_info.id ";

  $where = "where 0 ";

  if(0==strcmp('所有项目',$search_str)&&$_SESSION['logged']) {
    $where .= " or 1";
  } else if('未投运'==$search_str){
    $where .= " or committed=false";
  } else if('项目信息维护'==$search_str) {
    $where .= " maintainer_id = ".$_SESSION["user_id"];
  } else {
    $sql_str = "select id, name from user_info where name like '".$search_str."'";
    $rows = db_get($sql_str);
          
    if(count($rows) > 0){
      $user_id = $rows[0]['id'];
      $sub_where = " and ";
      $where .= "or (work_log.user_id = ".$user_id." and project_id in (select project_id from task_info where assignto = ".$rows[0]['id'].")) ";
    } else {
      $where .= " or project_name like '%$search_str%' or dw_no like '%$search_str%' or wbs_no like '%$search_str%'";
    }
  }
  
  $sql .= $where.$group;
  return $sql;
}

function gen_colleague_log_list($department_only) {
  $html_str = "";

  $common_fields = "name, date_format(end_time, '%a') end_time, w.title wtitle, w.content content, 
    updated_progress, work_hours, overtime_hours, w.last_modified last_modified";
  $where = " where user_id != ".$_SESSION['user_id'];
  if($department_only) {
    $where .= " and user_id in (select id from user_info where department_id = ". $_SESSION['department_id'].") ";
  }
  $sql = "select t.title ttitle, $common_fields from (user_info u, task_info t) join work_log w 
    on u.id=w.user_id and t.id = w.task_id $where
    union
    select '', $common_fields from user_info u join work_log w on u.id = w.user_id $where and task_id = 0
    order by last_modified desc limit 16";
    
  $rows = db_get($sql);
  foreach($rows as $row) {
    $disp_str = gen_sep_str(array($row['name'], $row['end_time'],
       $row['ttitle'],$row['wtitle'],$row['updated_progress']."%"), '，');
    $list_items[$disp_str] = $row['content'];
  }
  $html_str .= "<table width='65%' border=0><tr><td align='left' style='line-height:200%'>";
  $html_str .= "最新活动：<br>";
  $html_str .= gen_list_with_tip($list_items, 'ul');
  $html_str .= "</td></tr></table>";

  return $html_str;
}

function gen_latest_events() {
  $html_str = "";
  if($_SESSION['logged'] && is_senior_manager($_SESSION['user_id'])) {
    $html_str .= gen_colleague_log_list(0);
  }
  return $html_str;
}


function get_content() {
  $html_str = '';
  $html_str .= gen_query_form();

  if(isset($_POST['button']) || strcmp(key($_GET),"") != 0) {
    $search_str = get_search_str(get_query_str());
  
    if ((strpos($search_str, "足迹")!==false)&&$_SESSION['logged']) {
      $url = get_trace_link($search_str);
      if($url != "") {
        $html_str .= "<img src = '".$url."'/>";
      }
    } else {
      $sql = gen_sql_by_search_str($search_str);
      // echo 'sql str:'.$sql;
      $html_str .= gen_query_results($sql);
    }
  } else {
    $html_str .= gen_latest_events();
  }

  return $html_str; 
}

log_query_record();
log_visit();
proceed_project_commitment();

$content = get_content();
$login_required = 0;
echo gen_onecol_page($page_title, $content, $debug, $login_required);
?>
